package com.rr.prometheus8081.service;

import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Random;

/**
 * @author RR
 * @date 2021/7/18 15:41
 */
@Service
public class TimeActuatorService {

    @Autowired
    private MeterRegistry meterRegistry;

    private Counter oddCounter;
    private Counter evenCounter;

    @PostConstruct
    public void init() {
        //奇数计数器，tags为metric name和metric value
        oddCounter = meterRegistry.counter("odd counter", "name", "odd counter");
        oddCounter.increment();
        //偶数计数器，tags为metric name和metric value，也可以用builder来构建一个counter
        evenCounter = meterRegistry.counter("even counter", "name", "even counter");
        evenCounter.increment();
        //evenCounter = Counter.builder("even counter")
        //        .tag("name", "even counter")
        //        .register(meterRegistry);
    }

    @Scheduled(cron = "*/5 * * * * ?")
    //加上此注解后，能够收集它的方法执行次数，方法执行总耗时
    //有了上述两点信息，也可以得到平均耗时
    @Timed(description = "service.doOperation")
    public String doOperation() {
        int num = new Random().nextInt(100);
        try {
            Thread.sleep(num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (num % 2 == 0) {
            evenCounter.increment();
        } else {
            oddCounter.increment();
        }
        return String.valueOf(num);
    }
}
